package cn.diancan.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;

/**
 * sax 解析帮助工具类
 * @author Administrator
 *
 */
public class SaxParseXmlUtil {

	public static boolean parseXml(String fileName, DefaultHandler handler) {
		// 产生一个sax解析工厂，得到实例
		// 传递一个xml文件
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser xmlparse = factory.newSAXParser();
			InputStream input = new FileInputStream(fileName);
			xmlparse.parse(input, handler);
			input.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean parseXml(InputStream input, DefaultHandler handler) {
		// 产生一个sax解析工厂，得到实例
		// 传递一个xml文件
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser xmlparse = factory.newSAXParser();
			xmlparse.parse(input, handler);
			input.close();
			return true;
		} catch (Exception e) {
			System.out.println("sax 解析错误"+ e.getMessage() );
		}
		return false;
	}
	
	public static boolean parseXml(File file, DefaultHandler handler) {
		// 产生一个sax解析工厂，得到实例
		// 传递一个xml文件
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			if(null ==file ){
				System.out.println("文件为空" );
				return false;
			}
			SAXParser xmlparse = factory.newSAXParser();
			InputStream in = new FileInputStream(file);
			xmlparse.parse(in, handler);
			in.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("sax 解析错误"+ e.getMessage() );
		}
		return false;
	}
	
	//  InputStream input =  new FileInputStream("E:/ProgramFiles/apache-tomcat-6.0.36/webapps/ymmeituan3/WEB-INF/nuomi.com/20131105222128-20641756xiangtan.xml");  
    //  InputStream stream = SAXTuanXmlParse.class.getClassLoader().getResourceAsStream("Student.xml");

}
